# coding=utf-8

import os
import numpy as np
import re
import math


def read_data(path):
    lindata = open(path, 'r', encoding='utf-8')
    lines = [i for i in lindata if '-------' not in i if '..' not in i if ':' not in i]
    data = []
    for i in lines:
        if re.match(r'^(\-|\d)+', i) is not None:
            tmp = i.split(' ')
            tmp[-1] = tmp[-1].replace('\n', ',')
            data.append(tmp)
    data = np.array(data)
    data = data[:, 0:-1].astype(np.float32)
    return data


# 数据拟合
def yvalus(x, y, y_axisdd):
    x_axisd = np.array(x)
    y_axisd = np.array(y)
    z1 = np.polyfit(x_axisd, y_axisd, 1)  # 多项式拟合
    p1 = np.poly1d(z1)  # 拟合多项式的函数值
    print(p1)  # 打印拟合的多项式
    yvals = p1(x_axisd)  # 拟合后的y值
    ys = (y_axisdd - z1[1]) / z1[0]  # 1次多项式求根
    return yvals, ys


#读取model文件
model_name = 'model'
file_name = os.path.abspath('.') + '/model/' + model_name + '.txt'

def values(file_name, y_axisd):
    #**************  模型计算  ***************
    log_data = 2  #底数
    rddata = read_data(file_name)
    x_axis = np.log(rddata[1:, 0])/np.log(log_data)
    y_axis = abs((rddata[1:, 1] - rddata[0, 1])/rddata[0, 1]) * 100
    #****************************************
    nomald = math.pow(log_data, yvalus(x_axis, y_axis, y_axisd)[1])  # 解方程
    return nomald

def alg_process(content):
    lines = [i for i in content.split('\n') if '-------' not in i]
    data = []
    for i in lines:
        if re.match(r'^(\-|\d)+', i) is not None:
            tmp = i.split(' ')
            data.append(tmp)
    data = np.array(data)
    data = data[:, 0:-1].astype(np.float32) 
    x_axis = data[:, 0]
    x_axis /= 1000

    timea = 180   # 稳定时间
    timeb = 120   # 采样时间
    timec = 30   # 分析初始时间
    error_yaxisd = 2   # 响应阈值下限

    #读取value
    arr_value1 = []
    arr_value2 = []
    n_chanle = data.shape[1] - 5
    for ink in range(1, n_chanle):
        y_axis = data[:, ink]
        value1 = np.mean(y_axis[np.argwhere(np.logical_and(x_axis > (timea-timec), x_axis < timea))])
        value2 = np.mean(y_axis[np.argwhere(np.logical_and(x_axis > (timea+timeb-timec), x_axis < (timea+timeb)))])
        arr_value1.append(value1)
        arr_value2.append(value2)
    #print(n_chanle, arr_value1, arr_value2)
    
    nni = 0
    y_axisd = 0
    for nn in range(1, n_chanle):
        if arr_value1[nn] > 0.001 and (abs((arr_value2[nn] - arr_value1[nn]) / arr_value1[nn]) * 100 >= error_yaxisd):
            y_axisd += abs((arr_value2[nn] - arr_value1[nn]) / arr_value1[nn]) * 100
            nni += 1
    if nni > 0:
        #ret = y_axisd / nni
        ret = values(file_name, y_axisd/nni)
    else:
        ret = 0
    return "Concentration is: {} ug/kg".format(ret)  # 测试样本浓度
    #return "Value is: {} %".format(retd)  # 测试样本相对响应
